<script setup lang="ts">
defineOptions({
  name: "cpLineChart"
});
import { ref, computed } from "vue";
import { useDark, useECharts } from "@pureadmin/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import * as XLSX from "xlsx";
// 兼容dark主题
const { isDark } = useDark();
let theme = computed(() => {
  return isDark.value ? "dark" : "default";
});

const COLOR_PALETTE = [
  "#5470C6",
  "#EE6666",
  "#91CC75",
  "#FAC858",
  "#73C0DE",
  "#3BA272",
  "#FC8452",
  "#9A60B4",
  "#EA7CCC"
];

// 初始化ECharts
const chartRef = ref();
const { setOptions } = useECharts(chartRef, { theme });

const handleFileChange = async file => {
  try {
    const { xData, series } = await parseExcel(file.raw);

    setOptions({
      title: { text: "CP颗粒度监测数据", left: "center" },
      tooltip: {
        trigger: "axis"
      },
      xAxis: {
        type: "category",
        data: xData,
        axisLabel: { rotate: 45 }
      },
      yAxis: { type: "value" },
      series,
      grid: { containLabel: true, left: "3%", right: "3%" },
      legend: {
        data: series.map(s => s.name),
        bottom: 0
      }
    });
  } catch (error) {
    ElMessage.error(`文件解析失败，${error.message}`);
  }
};

const parseExcel = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => {
      try {
        const workbook = XLSX.read(e.target.result, { type: "array" });
        const worksheet = workbook.Sheets[workbook.SheetNames[0]];

        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        // 数据校验
        if (jsonData.length < 2) throw new Error("数据行数不足");

        // 提取数据（假设第一列为X轴，第二列为Y轴）
        const [headers, ...rows] = jsonData;
        const xData = rows.map(row => row[0]);

        const series = Array.from(
          { length: headers.length - 1 },
          (_, index) => {
            const colIndex = index + 1; // Y轴数据从第二列开始
            return {
              name: headers[colIndex],
              type: "line",
              smooth: true,
              data: rows.map(row => Number(row[colIndex])) || 0,
              itemStyle: {
                color: COLOR_PALETTE[index % COLOR_PALETTE.length]
              },
              lineStyle: {
                width: 2,
                type: index > 3 ? "dashed" : "solid" // 超过4个系列使用虚线
              }
            };
          }
        );

        resolve({ xData, series });
      } catch (error) {
        reject(error);
      }
    };
    reader.readAsArrayBuffer(file);
  });
};

const beforeUpload = file => {
  const isExcel = /\.(xlsx|xls)$/.test(file.name);
  if (!isExcel) {
    ElMessage.error("仅支持上传Excel文件!");
    return false;
  }
  return true;
};

setOptions({
  title: { text: "CP颗粒度监测数据", left: "center" },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  },
  xAxis: {
    type: "category",
    data: ["2025.1.3", "2025,1.10", "2025.1.17", "2025.1.24", "2025.1.31"]
  },
  yAxis: {
    type: "value"
  },
  legend: {
    bottom: "2%",
    left: "center"
  },
  series: [
    {
      name: "max(0.3um)",
      data: [2710, 13569, 4523, 4205, 13286],
      type: "line",
      symbol: "triangle",
      symbolSize: 20,
      lineStyle: {
        color: "#5470C6",
        width: 2,
        type: "dashed"
      },
      itemStyle: {
        borderWidth: 3,
        borderColor: "#EE6666",
        color: "yellow"
      }
    },
    {
      name: "max(0.5um)",
      data: [954, 15902, 2898, 1625, 11625],
      type: "line",
      symbol: "triangle",
      symbolSize: 20,
      lineStyle: {
        color: "#5443C6",
        width: 2,
        type: "dashed"
      },
      itemStyle: {
        borderWidth: 3,
        borderColor: "#EE6666",
        color: "yellow"
      }
    }
  ]
});
</script>

<template>
  <div style="width: 100%; height: 100vh">
    <div ref="chartRef" style="width: 100%; height: 70vh" />
    <el-upload
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-change="handleFileChange"
      accept=".xls,.xlsx"
      :auto-upload="false"
    >
      <el-button type="primary"> 上传Excel文件 </el-button>
    </el-upload>
  </div>
</template>
